package com.example.mp3player01.service;

import java.util.ArrayList;
import java.util.List;

import android.R;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.app.TaskStackBuilder;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;

import com.example.download.HttpDownloader;
import com.example.model.Mp3Info;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;

/**
 * Download service runs in background.
 * deparated.
 * Use asynctask instread of this seervice, since I need to update current UI thread.
 * 
 * @author congwang
 *
 */
public class DownloadService extends Service {
	
	private List<String> histories;

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		histories = new ArrayList<String>();
		
		Mp3Info mp3Info = (Mp3Info) intent.getSerializableExtra("mp3Info");
		
		histories.add(mp3Info.toString());
		
		DownloadThread downLoadThread = new DownloadThread(mp3Info);
		new Thread(downLoadThread).start();
		
		return super.onStartCommand(intent, flags, startId);
	}
	
	class DownloadThread implements Runnable {
		private Mp3Info mp3Info;
		
		public DownloadThread(Mp3Info mp3Info) {
			this.mp3Info = mp3Info;
		}
		
		public void run() {
			String mp3Url = "http://10.0.2.2:8080/mp3/" + mp3Info.getMp3Name();
			HttpDownloader downloader = new HttpDownloader();
			int result = downloader.downFile(mp3Url, "mp3/", mp3Info.getMp3Name());
			
			String resultMessage = null;
			if (result == -1) {
				resultMessage = "download failed.";
			} else if (result == 0) {
				resultMessage = "File is already downloaded.";
			} else if (result == 1) {
				resultMessage = "download successfully.";
			}  
			
			final String msg = resultMessage;
			
//			Request request = Request.newStatusUpdateRequest(Session.getActiveSession(), "", new Request.Callback() {
//                @Override
//                public void onCompleted(Response response) {
//                	new AlertDialog.Builder(DownloadService.this)
//                	.setMessage(msg)
//                	.setPositiveButton(R.string.ok, null)
//                	.show();
//                }
//            });
//			request.executeAsync();
			
			
			
		}
	}
	
	
	
	public List<String> getHistories() {
		return histories;
	}
	
}
